package org.dromara.system.controller.xcx;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.WbItemInfo;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.dto.NoteList;
import org.dromara.system.domain.dto.WbItemInfoGetDTO;
import org.dromara.system.domain.vo.*;
import org.dromara.system.service.*;
import org.dromara.system.utils.HttpClientUtil2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小程序-项目-公共接口
 *
 * @author Lion Li
 * @date 2024-05-08
 */


@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xcx/itemInfo")
public class XcxItemInfoController extends BaseController {
    private final String PC_DATA="{\"firstPageMenuId\": \"2018032900295987\",\"index\": 1,\"key\": \"\",\"orgId\": \"\",\"orgName\": \"\",\"purOrgCode\": \"\",\"purOrgStatus\": \"\",\"size\":\"100000\" }";

    private final String GJDW_URL="https://ecp.sgcc.com.cn/ecp2.0/ecpwcmcore//index/noteList";

    private final IWbItemInfoService wbItemInfoService;
    private final IWbItemFileService wbItemFileService;
    private final IWbMinuteBidBagService wbMinuteBidBagService;
    private final IWbDemandListService wbDemandListService;
    private final IWbGoodsListInfoService wbGoodsListInfoService;

    /**
     * 分包service层
     */
    private  final IWbGoodsListInfoService goodsListInfoService;

    private final IXcxFootprintService xcxFootprintService;

    /**
     * 查询货物清单列表
     */
    @GetMapping("/goodsListInfo/list")
    public TableDataInfo<WbGoodsListInfoVo> list(WbGoodsListInfoBo bo, PageQuery pageQuery) {
        return wbGoodsListInfoService.queryPageList(bo, pageQuery);
    }
    /**
     * 全部中标(含候选人)
     */
    @PostMapping("/allBidsWon")
    public TableDataInfo<WbMinuteBidBagVo> allBidsWon(@RequestBody WbMinuteBidBagBo bo, @RequestBody PageQuery pageQuery) {
        if(LoginHelper.getLoginUser() == null){
            return wbMinuteBidBagService.queryPageList_xcx(0L,bo, pageQuery);
        }else{
            return wbMinuteBidBagService.queryPageList_xcx(LoginHelper.getUserId(),bo, pageQuery);
        }
    }

    /**
     * 生成投标信息
     */
    @GetMapping("/generate/{id}")
    public R<WbItemInfoVo> generate(@NotNull(message = "主键不能为空")
                          @PathVariable Long id ) {
        WbItemInfoVo wbItemInfoVo = wbItemInfoService.queryGenerateBYId(id);
        return R.ok(wbItemInfoVo);
    }

    /**
     * 查询项目列表
     *
     */
    @PostMapping("/list")
    public TableDataInfo<WbItemInfoVo> list(@RequestBody WbItemInfoBo bo, @RequestBody PageQuery pageQuery) {

        return wbItemInfoService.queryPageList(bo, pageQuery);
    }

    @GetMapping("/listItemLogs")
    public TableDataInfo<WbItemInfoVo> listItemLogs(WbItemInfoBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        return wbItemInfoService.queryListItemLogs(bo,userId, pageQuery);
    }

    @PostMapping("/getInfo")
    public R getInfo() {
        try {
            List<WbItemInfo> wbItemInfoBos = new ArrayList<>();
            String s = HttpClientUtil2.doPost(GJDW_URL, PC_DATA);
            WbItemInfoGetDTO wbItemInfoGetDTO = JsonUtils.parseObject(s, WbItemInfoGetDTO.class);
            List<NoteList> noteLists = wbItemInfoGetDTO.getResultValue().getNoteList();
            for (NoteList note:noteLists){
                String itemName=note.getPublishOrgName()+note.getTitle();
                String itemId=note.getCode();
                String publishTime = note.getNoticePublishTime();
                WbItemInfo wbItemInfo = new WbItemInfo();
                wbItemInfo.setItemId(itemId);wbItemInfo.setItemName(itemName);wbItemInfo.setPublishTime(publishTime);
                wbItemInfoBos.add(wbItemInfo);
            }
            return wbItemInfoService.insertByBoList(wbItemInfoBos);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 导出项目列表
     */

    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WbItemInfoBo bo, HttpServletResponse response) {
        List<WbItemInfoVo> list = wbItemInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "项目", WbItemInfoVo.class, response);
    }





    /**
     * 获取项目详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R getInfo(@NotNull(message = "主键不能为空")
                     @PathVariable Long id ,String subStandardName, PageQuery pageQuery) {
        WbItemInfoVo wbItemInfoVo = wbItemInfoService.queryById(id);
//        String itemId = wbItemInfoVo.getItemId();
//        WbGoodsListInfoBo wbGoodsListInfoBo = new WbGoodsListInfoBo();
//        wbGoodsListInfoBo.setItemId(itemId);
        WbItemFileBo fileBo = new WbItemFileBo();
        fileBo.setItemId(wbItemInfoVo.getId());
        List<WbItemFileVo> wbItemFileVos = wbItemFileService.queryList(fileBo);
        Map<String,Object> map = new HashMap<>();
        map.put("ItemInfo",wbItemInfoVo);
//        map.put("goodsListInfoList",goodsListInfoService.queryPageList(wbGoodsListInfoBo, pageQuery));
        List<WbItemFileVo> wbItemFileVoss = new ArrayList<>();
        for (WbItemFileVo Vo1 : wbItemFileVos) {
            if (Vo1.getUrl().contains("zip")) {
                map.put("file_zip", Vo1);
            } else {
                wbItemFileVoss.add(Vo1);
            }
        }
        map.put("file",wbItemFileVoss);

        //查找对应id的分包
        TableDataInfo<WbDemandListVo> wbMinuteBidBagVoTableDataInfo = wbDemandListService.queryCountPageList(id,subStandardName, pageQuery);
        map.put("package",wbMinuteBidBagVoTableDataInfo);



        //保存我的足迹
        if (LoginHelper.getLoginUser() != null ){
            XcxFootprintBo xcxFootprintBo = new XcxFootprintBo();
            xcxFootprintBo.setFootprintId(id);
            xcxFootprintBo.setFootprintType("01");
            xcxFootprintBo.setCreateBy(LoginHelper.getUserId());
            //查询用户今天是否查看了这条数据，如果看了就更新，如果没看就添加
            XcxFootprintVo xcxFootprintVo = xcxFootprintService.queryListZYT(xcxFootprintBo);
            if (xcxFootprintVo == null){
                xcxFootprintService.insertByBo(xcxFootprintBo);
            }else {
                xcxFootprintBo.setId(xcxFootprintVo.getId());
                xcxFootprintService.updateByBo(xcxFootprintBo);
            }
        }

        return R.ok(map);
    }

    /**
     * 新增项目
     */
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WbItemInfoBo bo) {
        return toAjax(wbItemInfoService.insertByBo(bo));
    }

    /**
     * 修改项目
     */
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody WbItemInfoBo bo) {
        return toAjax(wbItemInfoService.updateByBo(bo));
    }

    /**
     * 删除项目
     *
     * @param ids 主键串
     */
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(wbItemInfoService.deleteWithValidByIds(List.of(ids), true));
    }
}
